package com.yakaten.service;

import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.io.IOUtils;
import org.seasar.framework.log.Logger;
import org.seasar.framework.util.ResourceUtil;

import com.yakaten.dto.AmazonItemInfoDto;
import com.yakaten.exception.AmazonException;

public class AmazonItemService {
	static Logger logger = Logger.getLogger(AmazonItemService.class);

	protected static final String REGEX_ITEM_NAME_NEW = "<h1 class=\"a-size-large a-spacing-none\">.+?</div>(.+?)</h1>";
	protected static final Pattern PATTERN_ITEM_NAME_NEW = Pattern.compile(
			REGEX_ITEM_NAME_NEW, Pattern.MULTILINE);

	protected static final String REGEX_TBODY_RESULT_NEW = "<div class=\"a-row a-spacing-mini olpOffer\">.+?<span class=\"a-size-large a-color-price olpOfferPrice a-text-bold\">.+?￥ (.+?)</span>.+?<p class=\"a-spacing-small olpSellerName\">(.+?)</p>.+?</div>";
	protected static final Pattern PATTERN_TBODY_RESULT_NEW = Pattern.compile(
			REGEX_TBODY_RESULT_NEW, Pattern.MULTILINE);


	protected static final String REGEX_SHIPPINGPRICE_NEW = "<span class=\"olpShippingPrice\">￥ (.+?)</span>";
	protected static final Pattern PATTERN_SHIPPINGPRICE_NEW = Pattern.compile(
			REGEX_SHIPPINGPRICE_NEW, Pattern.MULTILINE);


	protected static final String REGEX_SHOPNAME1_NEW = "<span class=\"a-size-medium a-text-bold\">.+?<a href=\".+?\">(.+?)</a>.+?</span>";
	protected static final Pattern PATTERN_SHOPNAME1_NEW = Pattern.compile(
			REGEX_SHOPNAME1_NEW, Pattern.MULTILINE);


	protected static final String REGEX_SHOPNAME2_NEW = "<a href=\"http://www.amazon.co.jp/shops/(.+?)/.+?\">.+?</a>";
	protected static final Pattern PATTERN_SHOPNAME2_NEW = Pattern.compile(
			REGEX_SHOPNAME2_NEW, Pattern.MULTILINE);

	protected static final String REGEX_SHOPNAME3_NEW = "<div class=\"sellerLogo\">.+?</div>.+?<h1>(.+?)</h1>";
	protected static final Pattern PATTERN_SHOPNAME3_NEW = Pattern.compile(
			REGEX_SHOPNAME3_NEW, Pattern.MULTILINE);


	protected static final String REGEX_SHOP_ITEM_NAME = "<span id=\"item_name_display\">(.+?)</span>";
	protected static final Pattern PATTERN_SHOP_ITEM_NAME = Pattern.compile(
			REGEX_SHOP_ITEM_NAME, Pattern.MULTILINE);

	protected static final String REGEX_SHOP_ITEM_DIV = "<div id=\"attribute-offer\".+?>(.+?)</div>";
	protected static final Pattern PATTERN_SHOP_ITEM_DIV = Pattern.compile(
			REGEX_SHOP_ITEM_DIV, Pattern.MULTILINE);

	protected static final String REGEX_SHOP_ITEM_PRICE = "<input.+?name=\"our_price\".+?value=\"(.+?)\".+?>";
	protected static final Pattern PATTERN_SHOP_ITEM_PRICE = Pattern.compile(
			REGEX_SHOP_ITEM_PRICE, Pattern.MULTILINE);

	protected static final String REGEX_SHOP_ITEM_QUANTITY = "<input.+?name=\"Offer_Inventory_Quantity\".+?value=\"(.+?)\".+?>";
	protected static final Pattern PATTERN_SHOP_ITEM_QUANTITY = Pattern
			.compile(REGEX_SHOP_ITEM_QUANTITY, Pattern.MULTILINE);

	protected static final String REGEX_SHOP_ITEM_CONDITION = "<span id=\"offering_condition_display\">(.+?)</span>";
	protected static final Pattern PATTERN_SHOP_ITEM_CONDITION = Pattern
			.compile(REGEX_SHOP_ITEM_CONDITION, Pattern.MULTILINE);

	protected static final DecimalFormat PRICE_FORMAT = new DecimalFormat(
			"###,###.###");

	public List<AmazonItemInfoDto> getItemInfo(String itemId, String condition)
			throws AmazonException {

		CookieManager manager = new CookieManager();
		manager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
		CookieHandler.setDefault(manager);

		List<AmazonItemInfoDto> resultList = new ArrayList<AmazonItemInfoDto>();

		String AMAZON_HOST = ResourceUtil.getProperties("yakaten.properties")
				.getProperty("amazon.host");

		String CONDITION_NEW = ResourceUtil.getProperties("yakaten.properties")
				.getProperty("amazon.condition.new");

		String CONDITION_USED = ResourceUtil
				.getProperties("yakaten.properties").getProperty(
						"amazon.condition.used");

		String url = AMAZON_HOST + itemId + "/";
		if ("1".equals(condition)) {
			url += CONDITION_NEW;
		} else if ("2".equals(condition)) {
			url += CONDITION_USED;
		}


		BufferedReader bufferedReader = null;
		HttpURLConnection connection = null;
		OutputStreamWriter out = null;

		try {
			URL loginUrl = new URL(url);
			connection = (HttpURLConnection) loginUrl.openConnection();
			connection
					.setRequestProperty(
							"User-Agent",
							"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.33 Safari/535.11");

			connection.connect();

			InputStream urlStream = connection.getInputStream();
			bufferedReader = new BufferedReader(new InputStreamReader(
					urlStream, "utf-8"));
			String ss = null;
			StringBuffer htmlBuffer = new StringBuffer();
			while ((ss = bufferedReader.readLine()) != null) {
				htmlBuffer.append(ss);
			}

			if("1".equals(ResourceUtil.getProperties("yakaten.properties").getProperty(
							"amazon.debug.on"))){
				IOUtils.write(htmlBuffer, new FileOutputStream("/var/www/vhosts/00_default/user/amazon.html"),"utf-8");
			}

			String price = "";
			String shippingPrice = "";
			String itemName = "";

			if (htmlBuffer != null) {

				//itemname
				Matcher matcherItemName = PATTERN_ITEM_NAME_NEW
						.matcher(htmlBuffer);
				if (matcherItemName.find()) {
					itemName = matcherItemName.group(1);
					itemName = itemName.trim();
				}

				Matcher matcherInputNew = PATTERN_TBODY_RESULT_NEW
						.matcher(htmlBuffer);

				//shop item info
				int count = 0;
				while (matcherInputNew.find()) {
					String shopName = "";
					AmazonItemInfoDto dto = new AmazonItemInfoDto();
					dto.setItemId(itemId);
					dto.setItemUrl(url);
					dto.setItemName(itemName);

					//price
					price = matcherInputNew.group(1);
					dto.setItemPrice(PRICE_FORMAT.parse(price).longValue());

					//shop_name
					if(count == 0){
						String sellerInformation = matcherInputNew.group(2);
						if (sellerInformation.length() > 0) {
							Matcher matcherShopName1 = PATTERN_SHOPNAME1_NEW
									.matcher(sellerInformation);
							if (matcherShopName1.find()) {
								shopName = matcherShopName1.group(1).trim();
							} else {
								Matcher sellerIdM = PATTERN_SHOPNAME2_NEW
										.matcher(sellerInformation);
								if(sellerIdM.find()){
									HttpURLConnection getShopNameConnection = null;
									BufferedReader getShopNameBufferedReader= null;
									try{
										String sellerId = sellerIdM.group(1);
										URL getShopNameUrl = new URL("http://www.amazon.co.jp/gp/aag/main/ref=olp_merch_rating_2?seller="+sellerId);
										 getShopNameConnection = (HttpURLConnection) getShopNameUrl.openConnection();
										getShopNameConnection
												.setRequestProperty(
														"User-Agent",
														"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.33 Safari/535.11");

										getShopNameConnection.connect();

										InputStream getShopNameUrlStream = getShopNameConnection.getInputStream();
										getShopNameBufferedReader = new BufferedReader(new InputStreamReader(
												getShopNameUrlStream, "shift_jis"));

										String getShopNameSs = null;
										StringBuffer getShopNameHtmlBuffer = new StringBuffer();
										while ((getShopNameSs = getShopNameBufferedReader.readLine()) != null) {
											getShopNameHtmlBuffer.append(getShopNameSs);
										}

//										IOUtils.write(getShopNameHtmlBuffer, new FileOutputStream("c:/amazonreview.html"),
//										"shift_jis");

										if ( getShopNameHtmlBuffer!= null) {
											Matcher getShopName = PATTERN_SHOPNAME3_NEW
											.matcher(getShopNameHtmlBuffer);

											if(getShopName.find()){
												shopName = getShopName.group(1).trim();
											}
										}

									}catch(Exception e){
										throw new AmazonException(e);
									}
									finally{
										if(getShopNameConnection!=null){
											getShopNameConnection.disconnect();
										}

										if(getShopNameBufferedReader!=null){
											getShopNameBufferedReader.close();
										}
									}

								}

							}

						}
					}
					dto.setShopName(shopName);

					//shipping price
					Matcher matcherShipping = PATTERN_SHIPPINGPRICE_NEW
							.matcher(matcherInputNew.group());
					if (matcherShipping.find()) {
						shippingPrice = matcherShipping.group(1);
						dto.setShippingPrice(PRICE_FORMAT.parse(shippingPrice)
								.longValue());
					}
					resultList.add(dto);
					count ++;
				}
			}

		} catch (IOException e) {
			throw new AmazonException(e);
		} catch (ParseException e) {
			throw new AmazonException(e);
		} finally {
			if (bufferedReader != null) {
				try {
					bufferedReader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (connection != null) {
				connection.disconnect();
			}

			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return resultList;

	}

	public AmazonItemInfoDto getShopItemInfo(String sku, String asin)
			throws AmazonException {
		AmazonItemInfoDto dto = new AmazonItemInfoDto();

		BufferedReader bufferedReader = null;
		HttpURLConnection connection = null;
		OutputStreamWriter out = null;
		try {
			String itemUrlStr = ResourceUtil
					.getProperties("yakaten.properties").getProperty(
							"amazon.shopitem.url");

			String marketplaceID = ResourceUtil.getProperties(
					"yakaten.properties").getProperty("amazon.mws.maketplace");

			URL itemUrl = new URL(itemUrlStr);

			connection = (HttpURLConnection) itemUrl.openConnection();
			connection
					.setRequestProperty(
							"User-Agent",
							"Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2");
			connection.setDoOutput(true);

			out = new OutputStreamWriter(connection.getOutputStream(),
					"shift_jis");

			out.write("sku=" + sku + "&asin=" + asin + "&marketplaceID="
					+ marketplaceID);
			out.flush();

			InputStream urlStream = connection.getInputStream();
			bufferedReader = new BufferedReader(new InputStreamReader(
					urlStream, "UTF-8"));
			String ss = null;
			StringBuffer total = new StringBuffer();
			while ((ss = bufferedReader.readLine()) != null) {
				total.append(ss);
			}

			Matcher matcherShopItemName = PATTERN_SHOP_ITEM_NAME.matcher(total);
			String shopItemName = "";
			if (matcherShopItemName.find()) {
				shopItemName = matcherShopItemName.group(1).trim().replaceAll(
						"\t", "");
			}

			Matcher matcherShopItemPrice = PATTERN_SHOP_ITEM_PRICE
					.matcher(total);
			long shopItemPrice = 0;
			if (matcherShopItemPrice.find()) {
				shopItemPrice = PRICE_FORMAT.parse(
						matcherShopItemPrice.group(1)).longValue();
			}

			Matcher matcherShopItemQuantiy = PATTERN_SHOP_ITEM_QUANTITY
					.matcher(total);
			String shopItemQuantity = "";
			if (matcherShopItemQuantiy.find()) {
				shopItemQuantity = matcherShopItemQuantiy.group(1);
			}

			Matcher matcherShopItemConditon = PATTERN_SHOP_ITEM_CONDITION
					.matcher(total);
			String shopItemCondition = "";
			if (matcherShopItemConditon.find()) {
				shopItemCondition = matcherShopItemConditon.group(1).trim()
						.replaceAll("\t", "");
			}

			dto.setShopItemName(shopItemName);
			dto.setShopItemPrice(shopItemPrice);
			dto.setShopItemQuantity(shopItemQuantity);
			dto.setShopItemCondition(shopItemCondition);
		} catch (MalformedURLException e) {
			throw new AmazonException(e);
		} catch (IOException e) {
			throw new AmazonException(e);
		} catch (ParseException e) {
			throw new AmazonException(e);
		} finally {
			if (bufferedReader != null) {
				try {
					bufferedReader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (connection != null) {
				connection.disconnect();
			}

			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return dto;
	}

	public static void main(String[] args) {

//		System.getProperties().put("proxySet", "true");
//
//		System.getProperties().put("proxyPort", "80");
//
//		System.getProperties().put("proxyHost", "proxysv");

		AmazonItemService service = new AmazonItemService();

		try {
			List<AmazonItemInfoDto> list = service.getItemInfo("B00428QRBC",
					"1");
			for (AmazonItemInfoDto current : list) {
				System.out.println(current.getShopName() + ":"
						+ current.getItemPrice() + ":"
						+ current.getShippingPrice() + ":"
						+ current.getItemName());
			}
		} catch (AmazonException e) {
			e.printStackTrace();
		}

	}
}
